//
//  SkectchMode.m
//  dataGathering
//
//  Created by apple on 14/12/23.
//  Copyright (c) 2014年 shuili. All rights reserved.
//

#import "SkectchMode.h"
#import "MySketchLayer.h"

@interface SkectchMode ()
@property(nonatomic, retain)MySketchLayer *mySketchLayer;
@end

@implementation SkectchMode

-(instancetype)initWithMapview :(AGSMapView*)mapview
{
    self = [super initWithMapview:mapview];
    if(self){
        [self.mapview removeMapLayer:self.myGraphicsLayer];
        _mySketchLayer= [[MySketchLayer alloc] initWithGeometry:nil];
        [self.mapview addMapLayer:_mySketchLayer withName:@"Sketch layer"];
        _mySketchLayer.mapView.touchDelegate = self;
        self.mapview.touchDelegate=_mySketchLayer;
        
        
        self.myPolygon = [[AGSMutablePolygon alloc] initWithSpatialReference:self.mapview.spatialReference];
         _mySketchLayer.geometry = self.myPolygon;
        
        //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(respondToGeomChanged:) name:AGSSketchGraphicsLayerGeometryDidChangeNotification object:nil];
    }
    return self;
}

- (void)respondToGeomChanged: (NSNotification*) notification {
    NSLog(@"numof points is %ld", (long)[(AGSPolygon*)[_mySketchLayer geometry] numPoints]);
    if([(AGSPolygon*)[_mySketchLayer geometry] numPoints] == 5){
        AGSPolygon* sketchGeometry = [_mySketchLayer.geometry copy];
        [self stop];
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(BaseMode:didFinishDrawing::)]) {
            [self.delegate BaseMode:self didFinishDrawing:sketchGeometry :@"POLYGON"];
        }
    }
}

-(void)mapView:(AGSMapView *)mapView didClickAtPoint:(CGPoint)screen mapPoint:(AGSPoint *)mappoint features:(NSDictionary *)features
{
    if([[AGSGeometryEngine defaultGeometryEngine] geometry:mappoint intersectsGeometry:_mySketchLayer.geometry])
    {
        AGSPolygon* sketchGeometry = [_mySketchLayer.geometry copy];
        [self stop];
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(BaseMode:didFinishDrawing::)]) {
            [self.delegate BaseMode:self didFinishDrawing:sketchGeometry :@"POLYGON"];
        }
    }
    
}

-(void)stop
{
    [super stop];
    //[[NSNotificationCenter defaultCenter] removeObserver:self name:AGSSketchGraphicsLayerGeometryDidChangeNotification object:nil];

    
}

@end
